<?php
session_start();

if(!isset($_SESSION['id'])){
	header('Location:login.php');
}
if(isset($_POST['submit'])){
	$id=intval($_POST['id']);
	$username=trim($_POST['username']);
	$password=trim($_POST['password']);
	$status=intval($_POST['status']);
	if($username==""||$password==""){
		echo "<script>alert('请输入用户名和密码！'); history.go(-1);</script>";
	}/*"/^[a-zA-Z]{1}[a-zA-Z0-9_]{2,9}$/"*/
	elseif(!preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z]{1}[\x{4e00}-\x{9fa5}a-zA-Z0-9]{2,9}+$/u",$username)){
		echo "<script>alert('用户名由中文、字母、数字组成;且首位不能为数字,长度在6~16个字符'); history.go(-1);</script>";
	}
	elseif(!preg_match("/^[a-zA-Z0-9]{6,16}$/",$password)){
		echo "<script>alert('密码由字母、数字组成;且长度在6~16个字符'); history.go(-1);</script>";
	}
	else{
		$db=new PDO("mysql:host=localhost;dbname=shenji","root","");
		$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
		$db->query("set names utf8");
		//$sql="select username from user where username='".mysql_real_escape_string($username)."'and password='".mysql_real_escape_string($password)."'";
		$sql="select count(*) from user where username=?";
		$result=$db->prepare($sql);
		$exeres=$result->execute(array($username));

		if($exeres){
			$row=$result->fetch(PDO::FETCH_NUM);
		}
		
		if($row[0]){
			echo "<script>alert('用户名已存在'); history.go(-1);</script>";
		}else{
			$sql1="insert into user(username,password,status) values(:username,:password,:status)";				
			$result1=$db->prepare($sql1);
			$result1->bindParam(':username',$username,PDO::PARAM_STR);
			$result1->bindParam(':password',md5($password),PDO::PARAM_STR);
			$result1->bindParam(':status',$status,PDO::PARAM_STR);
			$flag= $result1->execute();
			
			if($flag){
				echo "<script>alert('注册成功');location.href='select_user.php';</script>";
			}else{
				echo "<script>alert('注册失败'); history.go(-1);</script>";
			}
		}
		$db=null;
	}

}
?>
